/**
 * 开票
 */

/**
 * 验收
 */
'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Form,
  Input,
  Popconfirm,
  Row,
  Select,
  Statistic,
  Table,
  Tabs
} from 'antd';
import FormBase from '../../components/Base/FormBase';
import moment from 'moment';
import 'moment/locale/zh-cn';
import styles from "../index.less";
import ViewTitle from "../../components/ViewTitle";
import {FormField, ModalView, SearchForm} from "antd-extra";
import ModalCreateOrEditInvoiceRecord from "./modal/ModalCreateOrEditInvoiceRecord";
import ModalProcureOrderDetail from "../procure/modal/ModalProcureOrderDetail";
import ModalCreateOrEditInvoiceReceiptRecord from "./modal/ModalCreateOrEditInvoiceReceiptRecord";

moment.locale('zh-cn');
const {RangePicker} = DatePicker;
const _ = require('lodash');

const title = '收票';
const type = 'invoicingReceipt';
const {TabPane} = Tabs;
@Form.create()
@connect(({
            user,
            global,
            dict,
            finance
          }) => ({...user, ...global, ...finance, ...dict}))
export default class InvoicingReceipt extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();

    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    payload['type'] = type;
    console.log('payloadd', payload);
    dispatch && dispatch({
      type: 'finance/findInvoiceRecords',
      payload
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });

    this.props.dispatch({
      type: 'finance/invoiceReceiptAssess',
      payload
    });
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table: 'ProcureOrder'}
    });
  }

  cols() {
    return [
      {
        title: "供应商名称", dataIndex: 'name', key: 'name', render: (value, record) => {
          const {name, code} = record;
          return this.getProductionElement(code, name);
        }
      },

      {title: "收票公司", dataIndex: 'division', key: 'division'},
      {title: "收票金额", dataIndex: 'amount', key: 'amount'},
      {title: "税率", dataIndex: 'taxRate', key: 'taxRate'},
      {title: "发票号", dataIndex: 'invoiceNumber', key: 'invoiceNumber'},

      {
        title: "收票时间", dataIndex: 'createdTs', key: 'createdTs', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD HH:mm:ss')}</div>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160,
        render: (value, record) => {
          return (
            <span>
              {<a style={{marginRight: '6px'}} onClick={() => {
                this.onCreateOrEdit(record);
              }}>编辑</a>
              }
              {<Popconfirm
                title="确认删除"
                onConfirm={() => {
                  this.props.dispatch({
                    type: 'finance/deleteInvoiceRecord',
                    payload: record
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                }}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}}>删除</a>
              </Popconfirm>}
            </span>
          );
        }
      }
    ];
  }

  getSearchFields = () => {
    const {divisionDict} = this.props;
    return [
      <FormField
        label="供应商名称"
        name="name"
        key={1}
      >
        <Input allowClear placeholder={`请输入供应商名称`}/>
      </FormField>,
      <FormField
        label={'采购公司'}
        name={`division`}
        key={`division`}
      >
        <Select allowClear placeholder={`请输入${title}`}>{this.getDivision(divisionDict)}</Select>
      </FormField>,
      <FormField
        label={`统计时间`}
        name="createdTs"
        key={3}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>
    ];
  };
  onCreateOrEdit = (record) => {
    const _type = record ? 'finance/updateInvoiceRecord' : 'finance/createInvoiceRecord';
    ModalView.open(ModalCreateOrEditInvoiceReceiptRecord, {
      title: record ? "编辑" : "添加",
      width: '1280px'
    }, {
      record, entityType: '供应商', type,
      callback: (payload) => {
        payload.type = type;
        this.props.dispatch({
          type: _type,
          payload
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }

    });
  };

  materialCols() {
    return [
      {title: '采购单编码', dataIndex: 'procureOrderCode', key: 'procureOrderCode'},
      {title: '物料名称', dataIndex: 'name', key: 'name'},
      {title: '物料编码', dataIndex: 'code', key: 'code'},
      {title: '物料形态', dataIndex: 'subcategory', key: 'subcategory'},
      {title: '物料规格', dataIndex: 'spec', key: 'spec'},
      {title: '物料类型', dataIndex: 'type', key: 'type'},
      {title: '物料编号', dataIndex: 'number', key: 'number'},
      {title: '单价', dataIndex: 'price', key: 'price'},
      {title: '数量', dataIndex: 'count', key: 'count'},
      {title: '用途', dataIndex: 'target', key: 'target'},
      {title: '供应商', dataIndex: 'vendor', key: 'vendor'},
      {title: '采购类型', dataIndex: 'materialType', key: 'materialType'},
      {title: '采购公司', dataIndex: 'division', key: 'division'},
      {
        title: '是否开票', dataIndex: 'invoicingCount', key: 'invoicingCount', render: (value) => {
          const v = value && value > 0 ? "是" : '否';
          return <div>{v}</div>;
        }
      },
      {
        title: '采购日期', dataIndex: 'createdTs', key: 'createdTs', fixed: 'right', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      }
    ];
  }

  render() {
    const {form, invoicingReceiptRecords = [], procureInvoices = [], invoiceReceiptAssess = {}} = this.props;
    const {procureInvoiceTotal = 0, invoiceReceiptTotal = 0} = invoiceReceiptAssess;

    const {record = {}, showDetail} = this.state;

    return <Form className={styles.content}>
      <ViewTitle
        title={`收票统计`}
        level={1}
      ></ViewTitle>
      <SearchForm
        style={{marginLeft: '6px', marginRight: '6px'}}
        onSearch={() => {
          this.state.current = 1;
          this.componentDidMount();
        }}
        onReset={this.handleReset}
        cols={3}
        min={6}
        expandText="展开"
        form={form}
      >
        {this.getSearchFields()}
      </SearchForm>
      <div style={{background: '#ECECEC', padding: '30px'}}>
        <Row gutter={16}>
          <Col span={8}>
            <Card>
              <Statistic
                title="需收票采购单总金额"
                value={procureInvoiceTotal}
                precision={2}
                valueStyle={{color: '#3f8600'}}
                suffix="元"
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="已收票总金额"
                value={invoiceReceiptTotal}
                precision={2}
                valueStyle={{color: '#2222ff'}}
                suffix="元"
              />
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <Statistic
                title="未开票总金额"
                value={procureInvoiceTotal - invoiceReceiptTotal}
                precision={2}
                valueStyle={{color: '#cf1322'}}
                suffix="元"
              />
            </Card>
          </Col>
        </Row>
      </div>

      <ViewTitle
        title={`${title}记录列表`}
        level={1}
        actions={<Button type={'primary'} onClick={() => this.onCreateOrEdit()}>添加</Button>}
      ></ViewTitle>

      <Table
        className={styles.antTable}
        bordered={true}
        columns={this.cols()}
        dataSource={invoicingReceiptRecords}
        // scroll={{ x: true }}
        pagination={true}
      ></Table>


    </Form>;
  }
}

